package com.nami.dispatcher.domain.manager;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述：
 *
 * @Author: lbc
 * @Date: 2023-07-27 11:01
 * @email: 594599620@qq.com
 * @Description: keep coding
 */
@Slf4j
public class ThreadPoolManager {

    /**
     * TODO 需要反复压测，调到最优线程数大小
     * c2g
     */
    public static final ExecutorService GDISPATCHERS = new ThreadPoolExecutor(5, 10, 10L, TimeUnit.SECONDS,
        new LinkedBlockingDeque<>(50),
        ThreadFactoryBuilder
            .create()
            .setNamePrefix("DISPATCHER_G_")
            .setDaemon(true)
            .setUncaughtExceptionHandler(((thread, throwable) -> log.error("ThreadPool {} got exception", thread, throwable)))
            .build(),
        new ThreadPoolExecutor.CallerRunsPolicy() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            log.warn("[DISPATCHER-G] 线程爆炸了, 当前运行线程总数：{}，活动线程数：{}。等待队列已满，等待运行任务数：{}",
                e.getPoolSize(),
                e.getActiveCount(),
                e.getQueue().size());
        }
    });

    /**
     * c2c
     */
    public static final ExecutorService PDISPATCHERS = new ThreadPoolExecutor(10, 20, 10L, TimeUnit.SECONDS,
        new LinkedBlockingDeque<>(100),
        ThreadFactoryBuilder
            .create()
            .setNamePrefix("DISPATCHER_P_")
            .setDaemon(true)
            .setUncaughtExceptionHandler(((thread, throwable) -> log.error("ThreadPool {} got exception", thread, throwable)))
            .build(),
        new ThreadPoolExecutor.CallerRunsPolicy() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            log.warn("[DISPATCHER-G] 线程爆炸了, 当前运行线程总数：{}，活动线程数：{}。等待队列已满，等待运行任务数：{}",
                e.getPoolSize(),
                e.getActiveCount(),
                e.getQueue().size());
        }
    });


}


